
package yambal.net.google
{
	import flash.events.EventDispatcher;
	
	[Event(name="complete", type='flash.events.Event')]
	public class Authentication extends EventDispatcher
	{
		import flash.events.Event;
		import flash.net.URLLoader;
		import flash.net.URLRequest;
		import flash.net.URLVariables;
		
		private var _service:String;
		private var sid:String;
		private var lsid:String;
		private var _auth:String;

		public function Authentication()
		{
		}
		
		public function get service():String{
			return this._service;
		}
		
		public function get auth():String{
			return this._auth;
		}
		
		public function get is_ok():Boolean{
			if(this.sid != null && this.lsid != null && this.auth != null){
				return true;
			}else{
				return false;
			}
		}

		public function authenticate(email:String, password:String, service:String, isHosted:Boolean = false):void{
			this._service = service;
			this.sid = null;
			this.lsid = null;
			this._auth = null;
			
			var params:URLVariables = new URLVariables();
			params.Email = email;
			params.Passwd = password;
			params.service = service;
			
			if(isHosted){
				params.accountType = "HOSTED";
			}
			
			var loader:URLLoader = new URLLoader();
			
			loader.addEventListener(Event.COMPLETE, this.comp);
			
			var req:URLRequest = new URLRequest();
			req.url = "https://www.google.com/accounts/ClientLogin";
			req.method = "get";
			req.data = params;
			loader.load(req);
		}
		
		private function comp(e:Event):void{
			var loader:URLLoader = e.currentTarget as URLLoader;
			var res:Array = String(loader.data).split('\n');
			for(var i:int = 0; i<res.length; i++){
				var aug_split:Array = String(res[i]).split("=");
				if(aug_split.length>1){
					var aug_name:String = String(aug_split[0]).toLowerCase();
					var aug_value:String = String(aug_split[1]);
					switch (aug_name){
						case "sid":
							this.sid = aug_value;
							break;
						case "lsid":
							this.lsid = aug_value;
							break;
						case "auth":
							this._auth = aug_value;
							break;
						default:
							break;
					}
				}
			}
			
			if(this.sid != null && this.lsid != null && this.auth != null){
				trace('Authentication:OK');
				this.dispatchEvent(new Event(Event.COMPLETE));
			}else{
				trace('Authentication:Fault');
			}
		}
	}
}